<template>
  <el-dialog
    v-model="dialogVisible"
    title="查看详情"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="version-detail-dialog">
      <!-- 左侧导航 -->
      <div class="left-nav">
        <div
          v-for="item in navItems"
          :key="item.key"
          :class="['nav-item', { active: activeNav === item.key }]"
          @click="activeNav = item.key"
        >
          {{ item.label }}
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <!-- 基本信息 -->
        <div v-if="activeNav === 'basic'" class="content-panel">
          <div class="info-grid">
            <div class="info-item">
              <span class="label">物料编号：</span>
              <span class="value">{{ versionData.materialCode || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">物料名称：</span>
              <span class="value">{{ versionData.materialName || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">描述：</span>
              <span class="value">{{ versionData.remark || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">版本：</span>
              <span class="value">{{ versionData.version || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建人：</span>
              <span class="value">{{ versionData.createBy || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ versionData.createTime || '-' }}</span>
            </div>
          </div>
        </div>

        <!-- 字段配置 -->
        <div v-if="activeNav === 'field'" class="content-panel">
          <div class="tab-header">
            <el-button type="primary" @click="previewTemplate">预览</el-button>
            <el-input
              v-model="searchKeyword"
              placeholder="请输入字段名称/英文名称"
              clearable
              style="width: 300px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <el-table :data="filteredFieldData" v-loading="fieldLoading" border height="400">
            <el-table-column
              prop="fieldCategory"
              label="字段分类"
              width="150"
              show-overflow-tooltip
            />
            <el-table-column
              prop="fieldName"
              label="字段名称"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="fieldEnglishName"
              label="字段英文名称"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column prop="fieldType" label="字段类型" width="120" show-overflow-tooltip>
              <template #default="{ row }">
                {{ getFieldTypeName(row.fieldType) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="formula"
              align="center"
              label="计算公式"
              width="100"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.formula || '/' }}
              </template>
            </el-table-column>
            <el-table-column prop="isRequired" label="是否必填" width="100" show-overflow-tooltip>
              <template #default="{ row }">
                {{ row.isRequired ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-link type="primary" @click="viewFieldDetails(row)">查看详情</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 标签模板 -->
        <div v-if="activeNav === 'label'" class="content-panel">
          <div class="template-preview">
            <div class="template-content">
              <div v-for="(item, index) in labelItems" :key="index" class="template-row">
                <template v-if="item.type === 1">
                  <div class="template-field">
                    <span class="field-label">{{ item.fieldName }}：</span>
                    <span class="field-value">自动获取数据</span>
                  </div>
                </template>
                <template v-else-if="item.type === 2">
                  <div class="template-field">
                    <span class="field-label">{{ item.leftText }}：</span>
                    <span class="field-value">{{ item.rightText }}</span>
                  </div>
                </template>
                <template v-else-if="item.type === 3">
                  <div class="template-field">
                    <span class="field-label">条形码：</span>
                    <div class="barcode-container">
                      <div class="barcode-placeholder">
                        <div class="barcode-lines">
                          <div
                            class="barcode-line"
                            v-for="i in 20"
                            :key="i"
                            :style="{ width: Math.random() * 3 + 1 + 'px' }"
                          ></div>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
                <template v-else-if="item.type === 4">
                  <div class="template-field">
                    <span class="field-label">二维码：</span>
                    <div class="qrcode-container">
                      <div class="qrcode-placeholder">
                        <img src="@/assets/images/qrcode.png" alt="二维码" class="qrcode-image" />
                      </div>
                    </div>
                  </div>
                </template>
              </div>
              <div v-if="!labelItems || labelItems.length === 0" class="empty-state">
                <div class="empty-text">暂无标签配置</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加工工序 -->
        <div v-if="activeNav === 'process'" class="content-panel">
          <el-table :data="processTableData" border size="small">
            <el-table-column
              prop="step"
              label="步骤"
              width="200"
              header-align="center"
              align="center"
            />
            <el-table-column prop="name" label="操作" header-align="center" align="center" />
          </el-table>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>

    <!-- 字段预览对话框 -->
    <FieldPreviewDialog v-model:visible="previewVisible" :field-list="fieldData" />

    <!-- 字段详情对话框 -->
    <FieldDialog
      v-model:visible="fieldDetailVisible"
      :field-data="currentFieldData"
      :field-list="fieldData"
      :material-id="materialId"
      :readonly="true"
    />
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getById } from '@/api/system/materials'
import FieldPreviewDialog from './FieldPreviewDialog.vue'
import FieldDialog from './FieldDialog.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  versionId: {
    type: [String, Number],
    default: null
  },
  materialId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['update:visible'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const activeNav = ref('basic')
const navItems = [
  { key: 'basic', label: '基本信息' },
  { key: 'field', label: '字段配置' },
  { key: 'label', label: '标签模板' },
  { key: 'process', label: '加工工序' }
]

const versionData = ref({})
const fieldData = ref([])
const labelItems = computed(() => {
  const labelData = versionData.value?.labelConfigurationToEntity || []
  const fieldList = versionData.value?.fieldConfigurationToEntity || []

  if (!labelData || labelData.length === 0) {
    return []
  }

  return labelData.map((item) => {
    const convertedItem = {
      type: item.type || 1
    }

    if (item.type === 1) {
      const fieldId = item.id
      const field = fieldList.find((f) => f.id === fieldId || String(f.id) === String(fieldId))
      if (field) {
        convertedItem.fieldName = field.fieldName || ''
      } else {
        convertedItem.fieldName = '未知字段'
      }
    } else if (item.type === 2) {
      const valueParts = (item.value || '').split(',')
      convertedItem.leftText = valueParts[0] || ''
      convertedItem.rightText = valueParts[1] || ''
    }

    return convertedItem
  })
})

const processTableData = computed(() => {
  const processConfig = versionData.value?.processConfigurationToEntity || []
  return processConfig.map((item, index) => {
    const serialNumber = item.serialNumber || index + 1
    return {
      step: `步骤${getChineseNumber(serialNumber)}`,
      name: item.name || '-'
    }
  })
})

const fieldLoading = ref(false)
const searchKeyword = ref('')
const previewVisible = ref(false)
const fieldDetailVisible = ref(false)
const currentFieldData = ref(null)

const filteredFieldData = computed(() => {
  if (!searchKeyword.value.trim()) {
    return fieldData.value
  }

  const keyword = searchKeyword.value.toLowerCase()
  return fieldData.value.filter(
    (item) =>
      (item.fieldName && item.fieldName.toLowerCase().includes(keyword)) ||
      (item.fieldEnglishName && item.fieldEnglishName.toLowerCase().includes(keyword))
  )
})

// 获取版本详情
async function fetchVersionDetail() {
  if (!props.versionId) {
    ElMessage.warning('版本ID不存在')
    return
  }

  fieldLoading.value = true
  try {
    const res = await getById({ id: props.versionId })
    if (res.data) {
      versionData.value = res.data
      fieldData.value = res.data.fieldConfigurationToEntity || []
    }
  } catch (error) {
    ElMessage.error('获取版本详情失败')
    console.error('获取版本详情失败:', error)
  } finally {
    fieldLoading.value = false
  }
}

// 获取字段类型名称
function getFieldTypeName(fieldType) {
  return (
    {
      1: '两位小数',
      2: '整数',
      3: '日期',
      4: '文本',
      5: '枚举'
    }[fieldType] || '未知'
  )
}

// 将数字转换为中文数字
function getChineseNumber(num) {
  const chineseNumbers = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  if (num <= 10) {
    return chineseNumbers[num]
  } else if (num < 20) {
    return '十' + chineseNumbers[num - 10]
  } else if (num < 100) {
    const tens = Math.floor(num / 10)
    const ones = num % 10
    return chineseNumbers[tens] + '十' + (ones > 0 ? chineseNumbers[ones] : '')
  }
  return num.toString()
}

function previewTemplate() {
  if (!fieldData.value || fieldData.value.length === 0) {
    ElMessage.warning('暂无字段数据可预览')
    return
  }
  previewVisible.value = true
}

function viewFieldDetails(row) {
  currentFieldData.value = row
  fieldDetailVisible.value = true
}

function handleClose() {
  dialogVisible.value = false
  activeNav.value = 'basic'
  versionData.value = {}
  fieldData.value = []
  searchKeyword.value = ''
}

// 监听 visible 变化，打开时获取数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.versionId) {
      fetchVersionDetail()
    }
  }
)
</script>

<style lang="scss" scoped>
.version-detail-dialog {
  display: flex;
  height: 600px;

  .left-nav {
    width: 200px;
    border-right: 1px solid #e4e7ed;
    padding: 20px 0;

    .nav-item {
      padding: 12px 20px;
      cursor: pointer;
      color: #606266;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
        color: #409eff;
      }

      &.active {
        background-color: #ecf5ff;
        color: #409eff;
        border-right: 3px solid #409eff;
      }
    }
  }

  .right-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;

    .content-panel {
      height: 100%;

      .info-grid {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .info-item {
          display: flex;
          align-items: center;

          .label {
            color: #606266;
            font-weight: 500;
            margin-right: 8px;
            min-width: 100px;
          }

          .value {
            color: #303133;
          }
        }
      }

      .tab-header {
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .template-preview {
        border: 1px solid #e9ecef;
        padding: 16px;
        max-width: 500px;

        .template-content {
          .template-row {
            display: flex;
            align-items: center;

            .template-field {
              display: flex;
              align-items: center;
              width: 100%;

              .field-label {
                color: #606266;
                font-weight: 500;
                min-width: 100px;
                margin-right: 12px;
              }

              .field-value {
                color: #303133;
                flex: 1;
              }

              .barcode-container,
              .qrcode-container {
                flex: 1;
                display: flex;
                justify-content: flex-start;

                .barcode-placeholder,
                .qrcode-placeholder {
                  border-radius: 4px;
                  padding-top: 12px;
                  display: flex;
                  flex-direction: column;

                  .barcode-lines {
                    display: flex;
                    align-items: center;
                    gap: 1px;

                    .barcode-line {
                      height: 40px;
                      background: #000;
                      display: inline-block;
                    }
                  }

                  .qrcode-image {
                    width: 80px;
                    height: 80px;
                    object-fit: contain;
                  }
                }
              }
            }
          }

          .empty-state {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px 0;

            .empty-text {
              color: #909399;
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}
</style>
